package b1.scenes.fight
{
	import Box2D.Collision.*;
	import Box2D.Collision.Shapes.*;
	import Box2D.Common.Math.*;
	import Box2D.Dynamics.*;
	
	import b1.conifg.*;
	import b1.conifg.story.FightConfig;
	import b1.controls.basic.*;
	import b1.net.*;
	import b1.players.*;
	import b1.scenes.*;
	import b1.scenes.home.*;
	import b1.utils.*;
	
	import com.greensock.*;
	
	import flash.display.Sprite;
	import flash.events.*;
	import flash.filters.*;
	import flash.geom.Point;
	import flash.media.Sound;
	import flash.media.SoundChannel;
	import flash.text.*;
	import flash.utils.Timer;

	public class Fight extends Sprite
	{
		//物理引擎世界
		public var world:b2World;
		public static const worldScale:int = 30;
		public static const velocityIterations:int = 10;
		public static const positionIterations:int = 10;
		public static const timeStep:Number = 1.0/30.0;
		//天空变色
		public var tweenTime:Number;
		public var color1:Array;
		public var color2:Array;
		
		//物体所在图层（背景之前，包裹、图标等之后）
		public var objectLayer:Sprite;
		//魔法层
		public var magicLayer:Sprite;
		//空间层
		public var controlLayer:Sprite;
		
		//左侧信息
		public var leftPlayerId:int;
		public var leftAnimalIds:Array;
		//右侧信息
		public var rightPlayerId:int;
		public var rightAnimalIds:Array;
		public var rightPlayerId2:int;
		//左侧动物
		public var leftAnimal:Animal;
		public var rightAnimal:Animal;
		public var rightAnimal2:Animal;
		//场景中的所有骨头
		public var bones:Array;
		//场景中的所有物理
		public var fightObjects:Array;
		
		public var armInhand:Arm;
		
		//场景中的所有动物
		public var animals:Array;
		//天空
		public var sky:Sky;
		//风
		public var wind:Wind;
		//石头
		public var stone:Stone;
		//草地位置
		private var grassPosition:int;
		//计时
		private var timer:Timer;
		
		//结束时间
		private var endTimeCountDown:int;
		//显示时间
		private var playTime:PlayTime;
//		//mouseType, 0没有装备; 1,有装备
//		public var mouseType:int;  
		
		private var vImage:Sprite;
		private var sImage:Sprite;
		
		private var winnerAnimalId:int;
		
		private var loseHeirloomId:int;
		
		private var loserAnimalId:int;
		//回调函数
		private var callBack:Function;
		//作案结果类型: -2, 惨不忍睹； -1, 失败，再接再厉； 1胜利； 2命悬一线；3摧枯拉朽; 4 毫发无伤;
		private var fightResultType:int;
		//结算经验
		private var addExp:int;
		//获取传家骨标识:true表示获得
//		private var heirloomsGetFlag:Boolean;
		private var winBones:int;
		//托管图标
		public var managedIcon:ManagedIcon;
		
//		//乌鸦随机事件出现时间
		private var crowTime:int;
		private var crowEvent:CrowEvent;
		
		//虚拟战场信息（和虚拟的BOSS战斗）
		public var fightConfig:FightConfig;
		//角度力度信息显示
		private var launcherTip:RoundRec;
		private var tipText:TextField;
		//结束标记
		public var endFightFlag:Boolean;
		//暂停标记
		public var pauseFightFlag:Boolean;
		//无限播放的声音
		private var soundChannel:SoundChannel;
		//新的勋章
		private var newHonours:Object;

		public function Fight(leftPlayerId:int, rightPlayerId:int, leftAnimalIds:Array, rightAnimalIds:Array, callBack:Function = null, fightConfig:FightConfig = null)
		{
			super();
			SceneContainer.getInstance().debug("Fight: leftPlayerId " + leftPlayerId + ", rightPlayerId " + rightPlayerId);
			//新手引导送装备
			if (SceneContainer.getInstance().step > 0)
			{
				var me:PlayerInfo = PlayerInfoHelper.getInstance().players[PlayerInfoHelper.getInstance().userId];
				var myAnimal:AnimalInfo = PlayerInfoHelper.getInstance().animals[me.ownAnimals[0]];
				var equipInfo:EquipInfo = new EquipInfo();
				equipInfo.id = -ServerHelper.getInstance().now();
				equipInfo.position = 0;
				equipInfo.objectIndex = 38;
				equipInfo.durability = 99;
				myAnimal.equips[equipInfo.position] = equipInfo;
				equipInfo = new EquipInfo();
				equipInfo.id = -ServerHelper.getInstance().now();
				equipInfo.position = 2;
				equipInfo.objectIndex = 39;
				equipInfo.durability = 99;
				myAnimal.equips[equipInfo.position] = equipInfo;
			}			
			this.leftPlayerId = leftPlayerId;
			this.rightPlayerId = rightPlayerId;
			this.leftAnimalIds = leftAnimalIds;
			this.rightAnimalIds = rightAnimalIds;
			this.fightConfig = fightConfig;
			prepareHpAndVp();
			
			this.callBack = callBack;		
			//天空
			sky = new Sky();
			addChild(sky);
			//特殊战斗
			if (fightConfig != null)
			{
				sky.addChild(new HomeBackground(fightConfig.backgroundIndex));
			}
			//一般战斗
			else 
			{
				sky.addChild(new HomeBackground(3));
			}
			//物体图层
			objectLayer = new Sprite();
			addChild(objectLayer);
			//魔法图层
			magicLayer = new Sprite();
			addChild(magicLayer);
			//控件图层
			controlLayer = new Sprite();
			addChild(controlLayer);
			//所有动物
			animals = new Array();
			//所有骨头
			bones = new Array();
			//所有物体
			fightObjects = new Array();
			//获取草地的位置
			this.grassPosition = 510;
			//准备物理世界
			prepareB2World();
			
			endFightFlag = false;
			pauseFightFlag = false;
			//左动物
			leftAnimal = new Animal(leftAnimalIds[0], true);
			leftAnimal.createB2Body(world, BFont.stageWidth / 4, grassPosition, leftAnimal.animalMc.animalWidth, leftAnimal.animalMc.animalHeight, 1, 0, false);
			leftAnimal.changePreparedBone();
			leftAnimal.startWalk();
			leftAnimal.addThreeBars(this, 0);
			animals.push(leftAnimal);
			objectLayer.addChild(leftAnimal);
			
			//石头
			var obstacleConfig:ObstacleConfig;
			if (fightConfig != null)
			{
				obstacleConfig = Config.obstacleConfigs[fightConfig.obstacleIndex] as ObstacleConfig;
				stone = new Stone(fightConfig.obstacleIndex);
			}
			else
			{
				obstacleConfig = Config.obstacleConfigs[0] as ObstacleConfig;
				stone = new Stone(0);
			}
			stone.createB2Body(world, (BFont.stageWidth - stone.width) / 2, grassPosition - stone.height - 50, stone.width, stone.height, obstacleConfig.density, obstacleConfig.restitution);
			objectLayer.addChild(stone);
			
			//右动物
			if (rightAnimalIds.length >= 2)
			{
				rightPlayerId2 = rightAnimalIds[1];
				rightAnimal2 = new Animal(rightAnimalIds[1], false);
				rightAnimal2.changePreparedBone();
				rightAnimal2.startWalk();
				rightAnimal2.addThreeBars(this, 1);
				objectLayer.addChild(rightAnimal2);
				animals.push(rightAnimal2);
				rightAnimal2.createB2Body(world, 700, grassPosition, rightAnimal2.animalMc.animalWidth, rightAnimal2.animalMc.animalHeight, 1, 0, false);
			}
			rightAnimal = new Animal(rightAnimalIds[0], false);
			rightAnimal.changePreparedBone();
			rightAnimal.startWalk();
			rightAnimal.addThreeBars(this, 0);			
			objectLayer.addChild(rightAnimal);
			rightAnimal.createB2Body(world, 3 * BFont.stageWidth / 4, grassPosition, rightAnimal.animalMc.animalWidth, rightAnimal.animalMc.animalHeight, 1, 0, false);
			animals.push(rightAnimal);
			if (fightConfig != null)
			{
				leftAnimal.speak2(fightConfig.leftMessage, 2);
				rightAnimal.speak2(fightConfig.rightMessage, 0);
			}
			else
			{
				leftAnimal.speak(0, 0);
				rightAnimal.speak(1, 2);
			}
			//证物袋
			var clueBag:ClueBag;
			if (rightPlayerId > 0)
			{
				clueBag = new ClueBag("ClueBag", 10, "收集罪犯掉落的线索");
				clueBag.x = BFont.stageWidth - 70;
				clueBag.y = 150;
				TweenLite.from(clueBag, 1, {delay: 2, x:BFont.stageWidth, alpha:0});
			}
			else if (rightPlayerId < 0)
			{
				clueBag = new ClueBag("Equip30", -10, "收集装备");
				clueBag.x = 25;
				clueBag.y = 150;
				TweenLite.from(clueBag, 1, {delay: 2, x:-60, alpha:0});
			}
			addChild(clueBag);
			
			//托管
			managedIcon = new ManagedIcon();
			managedIcon.disableManager();
			managedIcon.x = 15;
			managedIcon.y = 300;
			TweenLite.from(managedIcon, 1, {delay: 2, x:-60, alpha:0});
			addChild(managedIcon);
			
			
			//随机事件时间初始化
	 		crowTime =  Math.round(Math.random() * Config.crowFlyTime);
	 		crowEvent = new CrowEvent();

			//战斗时间
			timer = new Timer(1000);
			
			loseHeirloomId = -1;
			
			//加上包裹
			PackageNavigator.getInstance().open(this);
			
			//加载声音图标
			var soundIcon:SoundIcon = new SoundIcon();
			soundIcon.x = BFont.stageWidth - soundIcon.width - 15;
			soundIcon.y = 300;
			TweenLite.from(soundIcon, 1, {delay: 2, x:BFont.stageWidth, alpha:0});
			addChild(soundIcon);
			
			//加载V
			var VImage:Class = ResourceHelper.getInstance().getClassByName("charV");
			vImage = new VImage();
			vImage.x = 250;
			vImage.y = 120;
			vImage.height =210;
			vImage.width = 140;
			addChild(vImage);
			//加载S
			var SImage:Class = ResourceHelper.getInstance().getClassByName("charS");
			sImage = new SImage();
			sImage.x = vImage.x + vImage.width;
			sImage.y = vImage.y;
			sImage.height = 210;
			sImage.width = 140;
			addChild(sImage);
			TweenLite.delayedCall(2, gameBegin);
			
			//使用装备
			this.addEventListener(MouseEvent.CLICK, onAnimalClick);
			
//			this.addEventListener(MouseEvent.MOUSE_UP, onMouseUp);
//			this.addEventListener(MouseEvent.MOUSE_DOWN, onMouseDown);
//			this.addEventListener(MouseEvent.MOUSE_MOVE, onMouseMove);
		}
		
		//停止天空黑暗
		public function restoreColor():void
		{
			if (this.color1 != null)
			{
				tweenTime = 1;
				TweenLite.to(this, 5, {tweenTime:0, onUpdate:onSkyColorUpdate, onComplete: onRestoreColorComplete});
			}
		}
		
		private function onRestoreColorComplete():void
		{
			this.color1 = null;
			this.color2 = null;
		}
		
		//天空黑暗
		public function changeColor(color1:Array, color2:Array = null):void
		{
			if (color1 != null)
			{
				this.color1 = color1;
				this.color2 = color2;
				tweenTime = 0;
				TweenLite.to(this, 5, {tweenTime:1, onUpdate:onSkyColorUpdate});
			}
		}
		
		//天空渐变响应
		private function onSkyColorUpdate():void
		{
			var colorFilter1:Array = new Array();
			var colorFilter2:Array = new Array();
			for (var i:int = 0; i < BFont.normalFilter.length; i++)
			{
				var filterElem:Number = color1[i] * tweenTime + BFont.normalFilter[i] * (1 - tweenTime); 
				colorFilter1.push(filterElem);
				if (color2 != null)
				{
					filterElem = color2[i] * tweenTime + BFont.normalFilter[i] * (1 - tweenTime);
					colorFilter2.push(filterElem);
				}
			}
			if (color2 == null)
			{
				sky.filters = [new ColorMatrixFilter(colorFilter1)];
				objectLayer.filters = [new ColorMatrixFilter(colorFilter1)];
			}
			else
			{
				sky.filters = [new ColorMatrixFilter(colorFilter1), new ColorMatrixFilter(colorFilter2)];
				objectLayer.filters = [new ColorMatrixFilter(colorFilter1), new ColorMatrixFilter(colorFilter2)];
			}
		}
		
		//暂停游戏
		public function pauseGame():void
		{
			pauseFightFlag = true;
			for (var i:int = 0; i < this.animals.length; i++)
			{
				(this.animals[i] as Animal).progressBar.stop();
				(this.animals[i] as Animal).stopWalk();
			}
		}
		
		public function resumeGame():void
		{
			pauseFightFlag = false;
			for (var i:int = 0; i < this.animals.length; i++)
			{
				(this.animals[i] as Animal).progressBar.resume();
				(this.animals[i] as Animal).startWalk();
			}
		}
		
		private function onMouseDown(event:MouseEvent):void
		{
			var launcher:Launcher = this.leftAnimal.launcher;
			if (this.endFightFlag)
			{
				launcher.dragFlag = false;
				return;
			} 
			var globalPoint:Point = event.target.parent.localToGlobal(new Point(event.target.x, event.target.y));
			if (globalPoint.x == 0 && globalPoint.y == 0)
			{
				launcher.dragFlag = true;
			}
		}
		
		private function onMouseUp(event:MouseEvent):void
		{
			var launcher:Launcher = this.leftAnimal.launcher; 
			if (launcher.dragFlag && this.leftAnimal.progressBar.reachRightEdgeFlag && !this.endFightFlag)
			{
				//消耗物品
				leftAnimal.consumeObject(launcher.preparedBone.index);
				//发射骨头
				var vitalityUsed:Number = launcher.launchPrepareBone();
				//消耗体力
				leftAnimal.vitalityChange(-vitalityUsed);
				//继续
				leftAnimal.progressBar.resume();
			}
			launcher.dragFlag = false;
		}
		
		private function onMouseMove(event:MouseEvent):void
		{
			//使用道具
			if (null != armInhand)
			{
				armInhand.x = stage.mouseX;
				armInhand.y = stage.mouseY;
			}
			//瞄准弓箭
			else
			{
				var launcher:Launcher = this.leftAnimal.launcher;			
				if (launcher.dragFlag)
				{
					var leftAnimalInfo:AnimalInfo = PlayerInfoHelper.getInstance().animals[leftAnimalIds[0]];
					var launcherX:Number = this.leftAnimal.x + launcher.x;
					var launcherY:Number = this.leftAnimal.y + launcher.y;
					var dist:Number = Math.sqrt((stage.mouseX - launcherX) * (stage.mouseX - launcherX) + (stage.mouseY - launcherY) * (stage.mouseY - launcherY));
					launcher.rotation = -180 * Math.atan2((stage.mouseX - launcherX), (stage.mouseY - launcherY)) / Math.PI; 
					launcher.setBoneByDistance(dist, leftAnimalInfo.vitalityPoint);
					addLauncherInformation(launcher.rotation, launcher.currentVitality);
					//添加新手导引
					if (SceneContainer.getInstance().step == 17 )
						SceneContainer.getInstance().addStep();
				}
				else
				{
					removeLauncherInformation();
				}
			}
		}
		
		//添加角度、力量等信息
		private function addLauncherInformation(launcherRotation:Number, launcherForce:Number):void
		{
			var rotation:int =  90 - Math.round(launcherRotation);
			if (rotation < 0)
			{
				rotation = 360 + rotation;
			}
			var textStr:String = "角度：" + rotation + "\n" + "力量：" + launcherForce;
			if (null == launcherTip)
			{
				launcherTip = new RoundRec(100, 50);
				addChild(launcherTip);
				tipText= new TextField();
				tipText.selectable = false;
	        	tipText.autoSize = TextFieldAutoSize.LEFT;
				tipText.defaultTextFormat = new TextFormat("微软雅黑", 15, 0x000000);
				tipText.text = textStr;
				tipText.x = (launcherTip.width - tipText.width) / 2;
				tipText.y = (launcherTip.height - tipText.height) / 2;
				launcherTip.addChild(tipText);
				launcherTip.x = this.leftAnimal.x - launcherTip.width / 2;
				launcherTip.y = 280;
			}
			else
			{
				tipText.text = textStr;
			}
		}
		
		//去掉角度、力量等信息
		private function removeLauncherInformation():void
		{
			if (null != launcherTip && null != launcherTip.parent)
			{
				launcherTip.parent.removeChild(launcherTip);
				launcherTip = null;
			}
		}
		
		
		//准备Box2D物理引擎世界
		public function prepareB2World():void
		{
			//准备物理世界
			world = new b2World(new b2Vec2(0, 10.0), true);
			var debugDraw:b2DebugDraw = new b2DebugDraw();
			var debugSprite:Sprite = new Sprite();
			objectLayer.addChild(debugSprite);
			debugDraw.SetSprite(debugSprite);
			debugDraw.SetDrawScale(worldScale);
			debugDraw.SetFlags(b2DebugDraw.e_shapeBit);
			world.SetDebugDraw(debugDraw);
			var objectContactListener:ObjectContactListener = new ObjectContactListener();  
			world.SetContactListener(objectContactListener);  
			objectContactListener.eventDispatcher.addEventListener(ObjectContactEvent.CONTACT, onObjectContact);
			//设置边界
			addB2Box(BFont.stageWidth / 2, grassPosition, BFont.stageWidth, 10, false, "ground");
			//设置更新
			addEventListener(Event.ENTER_FRAME, onB2WorldUpdate, false, 0, true);
		}
		
		//更新Box2D物理世界
		public function onB2WorldUpdate(e:Event):void 
		{
			world.Step(timeStep, velocityIterations, positionIterations);
			world.ClearForces();
			if (Profile.DEBUG)
				world.DrawDebugData();

			// Go through body list and update sprite positions/rotations
			for (var bb:b2Body = world.GetBodyList(); bb; bb = bb.GetNext())
			{
				if (bb.GetUserData() is FightObject)
				{
					var fightObject:FightObject = bb.GetUserData() as FightObject;
					fightObject.x = bb.GetPosition().x * worldScale;
					fightObject.y = bb.GetPosition().y * worldScale;
					fightObject.rotation = bb.GetAngle() * (180 / Math.PI);
				}
			}
		}
		
		//物理发生碰撞时候的处理函数
		private function onObjectContact(event:ObjectContactEvent):void
		{
			var hitAnimal:Animal = null;
			var hitBone:Bone = null;
			var hitPoint:HotPoint = null;
            var objectA:Object = event.contact.GetFixtureA().GetBody().GetUserData();  
            var objectB:Object = event.contact.GetFixtureB().GetBody().GetUserData();
        	var hitPointA:HotPoint = event.contact.GetFixtureA().GetUserData();
        	var hitPointB:HotPoint = event.contact.GetFixtureB().GetUserData();
        	var manifold:b2WorldManifold = new b2WorldManifold();
        	event.contact.GetWorldManifold(manifold);
            if (objectA is Animal && objectB is Bone)
            {
            	hitAnimal = objectA as Animal;
            	hitBone = objectB as Bone;
            	hitPoint = hitPointA as HotPoint;
            }
            else if (objectB is Animal && objectA is Bone)
            {
            	hitAnimal = objectB as Animal;
            	hitBone = objectA as Bone;
            	hitPoint = hitPointB as HotPoint;
            }
            var impulseSum:Number = 0;
            for (var i:int = 0; i < event.contact.GetManifold().m_pointCount; i++)
            {
            	impulseSum += event.impulse.normalImpulses[i];
            	var point:b2Vec2 = manifold.m_points[i];
            	var star:CollisionStar = new CollisionStar();
            	star.x = point.x * worldScale;
            	star.y = point.y * worldScale;
            	addChild(star);
            }
            var damage:Number = impulseSum;
            if (hitAnimal != null)
            {
	            trace("boneIndex:", hitBone.index, "damage:", damage);
        		hitAnimal.hitByBone(hitBone, hitPoint, damage);
            }
			//播放音效
			var SoundBow:Class = ResourceHelper.getInstance().getClassByName("SoundHit1");
			var sound:Sound = new SoundBow();
			sound.play(); 
		}
		
		//加载边界盒子
		public function addB2Box(px:Number, py:Number, w:Number, h:Number, dynamicFlag:Boolean, userData:Object):void 
		{
			var boxBodyDef:b2BodyDef = new b2BodyDef();
			boxBodyDef.position.Set(px/worldScale, py/worldScale);
			if (dynamicFlag) {
				boxBodyDef.type = b2Body.b2_dynamicBody;
			}
			var boxShape:b2PolygonShape = new b2PolygonShape();
			boxShape.SetAsBox(w/2/worldScale, h/2/worldScale);
			var boxFixture:b2FixtureDef = new b2FixtureDef();
			boxFixture.shape = boxShape;
			var boxBody:b2Body = world.CreateBody(boxBodyDef);
			boxBody.SetUserData(userData);
			boxBody.CreateFixture(boxFixture);
		}
		
		private function onAnimalClick(event:MouseEvent):void
		{
			if (armInhand != null)
			{
				for (var i:int = 0; i < this.animals.length; i++)
				{
					var animal:Animal = this.animals[i];
					if (this.mouseX <= animal.x + animal.width && this.mouseX >= animal.x - animal.width && this.mouseY  <= animal.y && this.mouseY >= animal.y - animal.height - 60)
					{
						//播放倒药剂动画
						TweenLite.to(armInhand, 0.5, {rotation: -120, onComplete:onUsePostion, onCompleteParams:[animal]});
						break;
					}
				}
			}
		}
		
		//使用药剂相应
		private function onUsePostion(targetAnimal:Animal):void
		{
			targetAnimal.usePotion(armInhand.index);
			leftAnimal.consumeObject(armInhand.index);
			removeArmInhand();
			if (SceneContainer.getInstance().step == 25)
			{
				SceneContainer.getInstance().clearLastStep();
				SceneContainer.getInstance().addStep();
			}
		}	
		
		//去掉原来的道具，添加新的道具道具
		public function addArm(objectIndex:int):void
		{
			removeArmInhand();
			addChildArmInhand(objectIndex);
		}
		
		//去掉道具
		public function removeArmInhand():void
		{
			if (null != armInhand && null != armInhand.parent)
			{
				armInhand.removeEventListener(MouseEvent.MOUSE_MOVE, onMouseMove);
				armInhand.parent.removeChild(armInhand);
			}
			armInhand = null;
		}
		
		//添加道具
		private function addChildArmInhand(objectIndex:int):void
		{
			armInhand = new Arm(objectIndex);
			armInhand.rotation = -30;
			addChild(armInhand);
			addEventListener(MouseEvent.MOUSE_MOVE, onMouseMove);
		}
		
		//准备生命值和体力值
		private function prepareHpAndVp():void
		{
			var animalInfo:AnimalInfo;
			for (var i:int = 0; i < leftAnimalIds.length; i++)
			{
				animalInfo = PlayerInfoHelper.getInstance().animals[leftAnimalIds[i]];
				animalInfo.healthPoint = animalInfo.currentHealthPoint;
				animalInfo.vitalityPoint = animalInfo.currentVitalityPoint;
				animalInfo.hpSaveTime = ServerHelper.getInstance().now();
			}
			for (i = 0; i < rightAnimalIds.length; i++)
			{
				animalInfo = PlayerInfoHelper.getInstance().animals[rightAnimalIds[i]];
				animalInfo.healthPoint = animalInfo.currentHealthPoint;
				animalInfo.vitalityPoint = animalInfo.currentVitalityPoint;
				animalInfo.hpSaveTime = ServerHelper.getInstance().now();
			}
		}
		
		private function gameBegin():void
		{
			TweenLite.to(vImage, 1, {x:0, y:vImage.y, alpha:0, onComplete:gameGo});
			TweenLite.to(sImage, 1, {x:700, y:vImage.y, alpha:0});
		}
		
		private function gameGo():void
		{
			removeChild(vImage);
			removeChild(sImage);
			fightGameStart();
		}
		
		//开始游戏
		public function fightGameStart():void
		{
			//加载无限播放的无声音乐（用于解决最小化战斗停止的bug）
			var SoundBird:Class = ResourceHelper.getInstance().getClassByName("SoundBird" + Clock.currentSeason);
			var soundNeverStop:Sound = new SoundBird();
			soundChannel = soundNeverStop.play(0, 10000);
			 
			this.leftAnimal.progressBar.resume();
			this.rightAnimal.progressBar.resume();
			timerStart();
			if (this.rightAnimalIds.length >= 2)
			{
				this.rightAnimal2.progressBar.resume();
			}
		}
	
		//计时开始
		public function timerStart():void
		{
			timer.start();
			timer.addEventListener(TimerEvent.TIMER, fightOnTick);
			playTime = new PlayTime();
			playTime.x = (BFont.stageWidth - playTime.width) / 2;
			playTime.y = 10;
			TweenLite.from(playTime, 1, {y:-80, alpha:0});
			addChild(playTime);		
			endTimeCountDown = Config.duration; 
		}
		
		//计时结束
		public function timeStop():void
		{
			timer.stop();
			timer.removeEventListener(TimerEvent.TIMER, fightOnTick);
			if (playTime != null && playTime.parent != null)
			{
				playTime.parent.removeChild(playTime);
			}
		}
		
		public function fightOnTick(event:TimerEvent):void
		{
			if (pauseFightFlag)
				return;			
			endTimeCountDown--;
			SceneContainer.getInstance().debug("Fight.fightOnTick: endTimeCountDown " + endTimeCountDown);
			if (endTimeCountDown > 0)
			{
//				if (!crowEvent.happenFlag && endTimeCountDown == crowTime) 
//				{
//					crowEvent.startFly();
//					this.objectLayer.addChild(crowEvent);
//				}
				playTime.update(endTimeCountDown);
				//遍历物体
				for (var i:int = 0; i < fightObjects.length; i++)
				{
					var fightObject:FightObject = fightObjects[i];
					fightObject.onFightTick();
				}
			}
			else
			{
				SceneContainer.getInstance().debug("Fight.fightOnTick: step " + SceneContainer.getInstance().step);
				//在新手引导中，时间到了也不结束游戏
				if (SceneContainer.getInstance().step > 0)
					return;
				//结束画面
				endGame();
			}
		}
		
		public function endGame():void
		{
			SceneContainer.getInstance().debug("endGame");
			//停止所有动画和timer
//			crowEvent.removeCrowEvent();
			timeStop();
			if (soundChannel != null)
				soundChannel.stop();
			this.endFightFlag = true;
			for (var i:int = 0; i < this.animals.length; i++)
			{
				(this.animals[i] as Animal).destroy();
			}
			for (i = 0; i < this.bones.length; i++)
			{
				(this.bones[i] as Bone).destroy();
			}
			var fightObject:FightObject = fightObjects.pop();
			while (fightObject != null)
			{
				fightObject.destroy();
				fightObject = fightObjects.pop();
			}
			//判断胜负
			var animals:Object = PlayerInfoHelper.getInstance().animals;
			var leftSideHealthPointSum:Number = 0;
			var leftSideHealthPointSumMax:Number = 0;
			for (i = 0; i < this.leftAnimalIds.length; i++)
			{
				var leftAnimalInfo:AnimalInfo = animals[leftAnimalIds[i]];
				leftSideHealthPointSum += leftAnimalInfo.healthPoint;
				leftSideHealthPointSumMax += leftAnimalInfo.healthPointMax;
			}
			var rightSideHealthPointSum:Number = 0;
			var rightSideHealthPointSumMax:Number = 0;
			for (i = 0; i < this.rightAnimalIds.length; i++)
			{
				var rightAnimalInfo:AnimalInfo = animals[rightAnimalIds[i]];
				rightSideHealthPointSum += rightAnimalInfo.healthPoint;
				rightSideHealthPointSumMax += rightAnimalInfo.healthPointMax;
			}
			//胜利
			if (leftSideHealthPointSum > rightSideHealthPointSum)
			{
				//秒杀
				if (leftSideHealthPointSum / leftSideHealthPointSumMax > 0.5 && rightSideHealthPointSum <= 0)
				{
					fightResultType = 4;
					if (fightConfig != null)
					{
							
					}
					else
					{
						leftAnimal.speak(2, 0);
					}
				}
				//完胜
				else if (leftSideHealthPointSum / leftSideHealthPointSumMax - rightSideHealthPointSum / rightSideHealthPointSumMax > 0.5)
				{
					fightResultType = 3;
					rightAnimal.speak(4, 1);
					leftAnimal.speak(3, 3);
				}
				//险胜				
				else if (leftSideHealthPointSum - rightSideHealthPointSum < leftSideHealthPointSumMax * 0.2)
				{
					fightResultType = 2;
					rightAnimal.speak(4, 1);
					leftAnimal.speak(3, 3);
				}
				//一般胜利
				else
				{
					fightResultType = 1;
					rightAnimal.speak(4, 1);
					leftAnimal.speak(3, 3);
				}
				winnerAnimalId = this.leftAnimal.animalId;
				loserAnimalId = this.rightAnimal.animalId;
			}
			//失败
			else
			{
				//完败
				if (rightSideHealthPointSum / rightSideHealthPointSumMax > 0.5 && leftSideHealthPointSum <= 0 || 
					rightSideHealthPointSum / rightSideHealthPointSumMax - leftSideHealthPointSum / leftSideHealthPointSumMax > 0.5)
				{
					fightResultType = -2;
				}
				else
				{
					fightResultType = -1;
				}
				leftAnimal.speak(4,1);
				rightAnimal.speak(3,3);
				winnerAnimalId = this.rightAnimal.animalId;
				loserAnimalId = this.leftAnimal.animalId;
			}
			//和服务器同步
			endConnect();
		}
		
		//和服务器进行同步
		private function endConnect():void
		{
			SceneContainer.getInstance().debug("endConnect");
			//计算左右侧的动物等级和
			var players:Object = PlayerInfoHelper.getInstance().players;
			var leftSideLevelSum:Number = 0;
			for (var i:int = 0; i < this.leftAnimalIds.length; i++)
			{
				var leftAnimalInfo:AnimalInfo = PlayerInfoHelper.getInstance().animals[leftAnimalIds[i]];
				leftSideLevelSum += leftAnimalInfo.level;
			}
			var rightSideLevelSum:Number = 0;
			for (i = 0; i < this.rightAnimalIds.length; i++)
			{
				var rightAnimalInfo:AnimalInfo = PlayerInfoHelper.getInstance().animals[rightAnimalIds[i]];
				rightSideLevelSum += rightAnimalInfo.level;
			}
			//结算经验 
			var heirloomLevelRatio:Number = rightSideLevelSum / (leftSideLevelSum + rightSideLevelSum);
			//得到传家骨的几率
			var getHeirloomPossibility:Number = 0;
			//得到的经验
			addExp = 0;
			//得到的骨头
			winBones = 0;
			var winLevel:int = Math.max(rightAnimalInfo.level - leftAnimalInfo.level + Config.levelBalance, 0);
			//计算不同胜利方式
			//秒杀
			if (fightResultType == 4)
			{
				addExp = (Config.baseExp + Config.addExpPerLevel * rightSideLevelSum) * Config.expRatioForPerfectWin;
				winBones = Math.max(winLevel * Config.timesBalance * Config.expRatioForPerfectWin, 1);
				getHeirloomPossibility = Config.heirloomRatioForPerfectWin * heirloomLevelRatio;
			}
			//完胜
			else if (fightResultType == 3)
			{
				addExp = (Config.baseExp + Config.addExpPerLevel * rightSideLevelSum) * Config.expRatioForGoodWin;
				winBones = Math.max(winLevel * Config.timesBalance * Config.expRatioForGoodWin, 1);
				getHeirloomPossibility = Config.heirloomRatioForGoodWin * heirloomLevelRatio;
			}
			//险胜
			else if (fightResultType == 2)
			{ 
				addExp = (Config.baseExp + Config.addExpPerLevel * rightSideLevelSum) * Config.expRatioForLittleWin;
				winBones = Math.max(winLevel * Config.timesBalance * Config.expRatioForLittleWin, 1);
				getHeirloomPossibility = Config.heirloomRatioForLittleWin * heirloomLevelRatio;
			}
			//一般胜利
			else if (fightResultType == 1) 
			{
				addExp = Config.baseExp + Config.addExpPerLevel * rightSideLevelSum;
				winBones = Math.max(winLevel * Config.timesBalance, 1);
				getHeirloomPossibility = Config.heirloomRatioForWin * heirloomLevelRatio;
			}
			//完败
			else if (fightResultType == -2)
			{
				getHeirloomPossibility = 0;
			}
			//惜败
			else 
			{
				getHeirloomPossibility = 0;
				addExp = Config.baseExp * Config.expRatioForLose;
			}
			//结算传家骨
			var heirloomBalance:String = "";
//			heirloomsGetFlag = false;
			if (Math.random() < getHeirloomPossibility)
			{
				if ((players[rightPlayerId] as PlayerInfo).heirlooms[leftPlayerId] != null)
				{
					this.loseHeirloomId = leftPlayerId;
					heirloomBalance += this.rightPlayerId + "," + this.leftPlayerId + "," + this.leftPlayerId + "," + this.leftPlayerId;
//					heirloomsGetFlag = true;
				}
				else
				{
					for (var heirIndex:String in (players[rightPlayerId] as PlayerInfo).heirlooms)
					{
						if ((players[rightPlayerId] as PlayerInfo).heirlooms[heirIndex] != null)
						{
							this.loseHeirloomId = parseInt(heirIndex);
							heirloomBalance += this.rightPlayerId + "," + ((players[rightPlayerId] as PlayerInfo).heirlooms[heirIndex] as Heirloom).originalOwnerPlayerId + "," + this.leftPlayerId + "," +((players[rightPlayerId] as PlayerInfo).heirlooms[heirIndex] as Heirloom).originalOwnerPlayerId;
//							heirloomsGetFlag = true;
							break;
						}
					}
				}
			}
			//结算战斗所消耗的物品，生命值和体力值
			var boneBalance:String = "";
			var hpBalance:String = "";
			for (i = 0; i < animals.length; i++)
			{
				var animal:Animal = animals[i];
				var animalInfo:AnimalInfo = PlayerInfoHelper.getInstance().animals[animal.animalId];
				var animalConfig:AnimalConfig = Config.animalConfigs[animalInfo.animalIndex];
				for (var indexStr:String in animal.consumedObjects)
				{
					if (boneBalance.length > 0)
						boneBalance += ",";
					var index:int = parseInt(indexStr);
					boneBalance += animalInfo.ownerId + "," + index + "," + (-animal.consumedObjects[index]);
				}
				if (hpBalance.length > 0)
					hpBalance += ",";
				hpBalance += animalInfo.id + "," + animalConfig.regainRate + "," + animal.addHealhPoint + "," + animal.addVitalityPoint;
			}
			//胜利时得到boss掉落的装备
			if (fightResultType > 0)
			{
				var honourBalance:String = "";
				for (var equipIndex:String in rightAnimal.bossEquipDrop)
				{
					if (boneBalance.length > 0)
						boneBalance += ",";
					var player:PlayerInfo = PlayerInfoHelper.getInstance().players[PlayerInfoHelper.getInstance().userId];
					if (player.userPackage.objectList[equipIndex] <= 0 || player.userPackage.objectList[equipIndex] == null)
					{
						var equipConfig:EquipConfig = Config.objectConfigs[equipIndex] as EquipConfig;
						if (player.checkNewHonour(equipConfig.index, rightAnimal.bossEquipDrop))
							honourBalance += PlayerInfoHelper.getInstance().userId + "," + equipConfig.equipType + "," + Config.equipColorScore[equipConfig.color] + ",";
					}
					boneBalance += this.leftPlayerId + "," + equipIndex + ",1";
				}	
			}
			if (boneBalance.length > 0)
				boneBalance += ",";
			boneBalance += this.leftPlayerId + "," + 0 + "," + winBones.toString();
			//结算经验
			//阵营对应的时段经验加成
			leftAnimalInfo = PlayerInfoHelper.getInstance().animals[leftAnimal.animalId];
			var leftAnimalConfig:AnimalConfig = Config.animalConfigs[leftAnimalInfo.animalIndex];
			if (leftAnimalConfig.camp == Clock.currentSeason)
			{
				addExp = (Config.expBonusForDayNight + 1) * addExp;
			}
			var levelExp:Array = AnimalInfo.getLevelByAddExp(leftAnimalInfo.level, leftAnimalInfo.experience, addExp);
			var expBalance:String = this.leftAnimal.animalId + "," + levelExp[0] + "," + addExp + "," + Config.skillPointsPerLevel;
			//与服务器同步
			ServerHelper.getInstance().endFight(this.leftPlayerId, this.rightPlayerId, this.leftAnimalIds, this.rightAnimalIds, hpBalance, boneBalance, expBalance, heirloomBalance, honourBalance, fightCallBack);
			TweenLite.delayedCall(6, showEndMovie);
		}
		
		//显示结束面板
		public function showEndMovie():void
		{
			var endPane:EndPane = new EndPane(fightResultType, winBones, addExp, loseHeirloomId, rightAnimal.bossEquipDrop);
			endPane.x = (BFont.stageWidth - endPane.width) / 2;
			endPane.y = (BFont.stageHeight - endPane.height) / 2;
			endPane.buttonOK.addEventListener(MouseEvent.CLICK, onClickEndOK);
			addChild(endPane);
			
			//添加新手导引
			if (SceneContainer.getInstance().step == 27)
				SceneContainer.getInstance().addStep();
		}
		
		public function fightCallBack(newHonours:Object):void
		{
			this.newHonours = newHonours;
		}
		
		public function onClickEndOK(event:MouseEvent):void
		{
			//重置先前进入的场景
			SceneContainer.getInstance().loadPreviousScene();
			//回调函数
			if (this.callBack != null)
			{
				this.callBack(leftPlayerId, rightPlayerId, winnerAnimalId, loserAnimalId, winBones, loseHeirloomId, leftAnimal.animalCluesDrop, fightConfig, newHonours);
			}
			
		}
	}
}